package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.model.Thread;
import com.conversationboard.model.User;
import com.conversationboard.model.randomthread.RandomThread;

@WebServlet(name = "RandomThreadsControllerServlet", urlPatterns = "/RandomThreadsControllerServlet")
public class RandomThreadsControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -1440135531799009716L;
	private static final int NUMBER_OF_RANDOM_THREADS = 20;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			/*
			 * Get a list of random threads and pass them to the page for
			 * display
			 */

			User user = null;

			if (request.getUserPrincipal() == null) {
				user = User.getAnonymousUser();
			} else {
				user = User.get(request.getUserPrincipal());
			}

			List<RandomThread> randomThreads = Thread.getRandomThreads(user, NUMBER_OF_RANDOM_THREADS);

			request.setAttribute("randomThreads", randomThreads);

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/randomthreads.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}
	}

}